﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace UnityMethods.Extend
{
    public partial class Ext
    {
        /// <summary>
        /// 反射拷贝
        /// </summary>
        /// <typeparam name="TIn"></typeparam>
        /// <typeparam name="TOut"></typeparam>
        /// <param name="tIn"></param>
        /// <returns></returns>
        public static TOut TransCopyData<TIn, TOut>(TIn tIn)
        {
            TOut tOut = Activator.CreateInstance<TOut>();

            if (tIn != null && tOut != null)
            {
                var tInType = tIn.GetType();

                PropertyInfo[] tOutProperties = tOut.GetType().GetProperties().Where(x => !Attribute.IsDefined(x, typeof(NotMappedAttribute))).ToArray();

                foreach (var itemOut in tOutProperties)
                {
                    var itemIn = tInType.GetProperty(itemOut.Name); ;
                    if (itemIn != null)
                    {
                        itemOut.SetValue(tOut, itemIn.GetValue(tIn));
                    }
                }
            }

            return tOut;
        }
    }
}
